<?php
namespace app\index\controller;

use app\index\model\FileModel;
use app\index\model\FlowBillModel;
use app\index\model\FlowLogModel;
use app\index\model\FlowNodeModel;
use app\index\model\FlowPromerModel;
use app\index\model\FlowShareModel;
use app\index\model\FlowTalkModel;
use app\index\model\FlowTaskModel;
use app\index\model\FlowTaskShenModel;
use app\index\model\UserModel;
use app\index\service\FlowService;
use app\index\service\OptService;
use app\index\service\WorkerService;
use think\Db;
use think\Exception;
use think\Request;

class Flow extends Common
{
    public function examine_bill(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['status'] != 0){
            return outputJson(4000,lang('code_4006'));
        }
        $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);

        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        $myTask = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'state'=>1])
            ->where(['uid'=>$this->userinfo['id'],'deleted_user'=>0])->find();
        if(!$myTask){
            return outputJson(4000, '您不是审核人');
        }


        $node = FlowNodeModel::where(['id'=>$myTask['nodeid']])->find();
        if(!$node){
            return outputJson(4000,lang('code_4006'));
        }


        $qian_id = isset($param['qian_id']) ? $param['qian_id'] : '';
        $qian = isset($param['qian']) ? $param['qian'] : '';
        $ispc = isset($param['ispc']) ? $param['ispc'] : '';
        if(in_array($param['agree'], [1,2,3,4,5])){
            if($ispc == 1){
                if($this->cominfo['isqian'] == 1){
                    if(!$qian_id || !$qian){
                        return outputJson(4000, '请输入签名');
                    }
                }
            }else{
                if($this->cominfo['isqian'] > 0){
                    if(!$qian_id || !$qian){
                        return outputJson(4000, '请输入签名');
                    }
                }
            }
        }

        Db::startTrans();
        try {

            FlowBillModel::where(['id'=>$bill['id']])->update(['recall'=>0,'updated_at'=>date('Y-m-d H:i:s')]);
            FlowTaskShenModel::where(['billid'=>$bill['id']])->where('nodeid','neq',$node['id'])->update(['recall'=>0]);

            //当前任务如果是加签或者转签=====更新上级任务不能撤回审批
            if($myTask['opt'] == 'add' || $myTask['opt'] == 'zhuan'){
                FlowTaskShenModel::where(['billid'=>$bill['id'],'taskid'=>$myTask['pid']])->update(['recall'=>0]);
            }

            if($param['agree'] == 1){ //同意
                FlowNodeModel::where(['id'=>$myTask['nodeid']])->update(['onshen'=>$node['onshen'].','.$this->userinfo['id']]);

                if($node['type'] == 2){
                    if($param['isnext'] == 1){
                        if(!$param['nexter']){
                            return outputJson(4000, '请选择指定下一步审核人');
                        }
                        $nexterInfo = UserModel::where(['comid'=>$this->userinfo['comid'],'deleted_user'=>0,'id'=>$param['nexter']])->find();
                        if(!$nexterInfo){
                            throw new Exception("操作失败,当前选择的下一步审核人不存在，请重新选择");
                        }
                        $onshenArr = explode(',', $node['onshen']);
                        if(in_array($param['nexter'], $onshenArr)){
                            return outputJson(4000, '下一步审核人已在当前节点审核组,请重新选择');
                        }

                        FlowTaskModel::insert([
                            'comid' => $this->userinfo['comid'],
                            'billid' => $bill['id'],
                            'nodeid' => $myTask['nodeid'],
                            'pid' => $myTask['id'],
                            'name' => $myTask['name'],
                            'signtype' => 1,
                            'plain' => 0,
                            'uid' => $param['nexter'],
                            'isadd' => 0,
                            'opt' => 'next',
                            'addtype' => 1,
                            'addcate' => 1,
                            'state' => 1,
                            'created_at' => date("Y-m-d H:i:s"),
                        ]);
                        (new WorkerService())->add_worker_bill($param['nexter'], 'shen', $bill);
                        FlowTaskModel::where(['id'=>$myTask['id']])->update([
                            'state'=>2,'updated_at'=>date('Y-m-d H:i:s'),'deleted_user'=>1
                        ]);
                        FlowTaskShenModel::where(['billid'=>$bill['id']])->update(['recall'=>0]);
                        (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'next','同意',1,$param['promer'],$myTask['created_at']);
                    }else{
                        FlowTaskShenModel::insert([
                            'comid' => $this->userinfo['comid'],
                            'billid' => $bill['id'],
                            'nodeid' => $node['id'],
                            'taskid' => $myTask['id'],
                            'uid' => $this->userinfo['id'],
                            'opt' => 'next',
                            'name' => '同意',
                            'recall' => 0,
                            'created_at' => $myTask['created_at'],
                            'updated_at' => date("Y-m-d H:i:s"),
                        ]);

                        FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>1]);
                        Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>1]);
                        (new FlowService())->flow_bill_succ($bill);
                        $mess = "流程审核完成（同意）：您发起的".$bill['summary'];
                        (new OptService())->add_todo($bill['created_user'], $bill['modename'],$mess, $bill['mid'], $bill['modenum']);
                    }
                }else{
                    FlowTaskModel::where(['id'=>$myTask['id']])->update([
                        'state'=>2,'updated_at'=>date('Y-m-d H:i:s'),'deleted_user'=>1
                    ]);

                    (new FlowService())->flow_task_comple_linkage($myTask['id'], $minfo, $bill);

                    $existShen = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'deleted_user'=>0])
                        ->where('state','in',[0,1])->find();

                    if(!$existShen){
                        $nextNode = FlowNodeModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])
                            ->where('id','gt',$node['id'])->find();
                        if(!$nextNode){
                            FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>1]);
                            Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>1]);
                            (new FlowService())->flow_bill_succ($bill);
                            $mess = "流程审核完成（同意）：您发起的".$bill['summary'];
                            (new OptService())->add_todo($bill['created_user'], $bill['modename'],$mess, $bill['mid'], $bill['modenum']);

                        }else{
                            (new FlowService())->create_flow_node_task($nextNode, $minfo, $bill);
                        }
                    }

                    if($myTask['pid'] == 0){
                        (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'agree','同意',1,$param['promer'],$myTask['created_at']);
                    }else{
                        (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'agree','同意',0,$param['promer'],$myTask['created_at']);
                    }
                }
                (new OptService())->add_flow_shenlog($myTask, '同意',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
            }elseif($param['agree'] == 2){ //不同意
                FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>2]);
                Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>2]);

                (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'agreeno','不同意',0,$param['promer'],$myTask['created_at']);
                $mess = "审核完成（不同意）：您发起的[".$bill['summary']."]";
                (new OptService())->add_todo($bill['created_user'], $bill['modename'],$mess, $bill['mid'], $bill['modenum']);
                (new OptService())->add_flow_shenlog($myTask, '不同意',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
            }elseif($param['agree'] == 3){ //退回
                FlowTaskShenModel::where(['billid'=>$bill['id']])->update(['recall'=>0]);

                $tuitypeName = '';
                $tuierArr = [];
                $task_plain = 0;
                $task_signtype = 1;
                $task_nodeid = 0;
                $task_name = '';
                if($param['tuitype'] == 1){
                    $tuiidInfo = FlowTaskModel::where(['id'=>$param['tuiid']])->find();
                    $tuiidNode = FlowNodeModel::where(['id'=>$tuiidInfo['nodeid']])->find();
                    $tuiname = UserModel::get_realname_by_pk($tuiidInfo['inituid']);
                    $tuitypeName = $tuiidInfo['name']. ' '.$tuiname;
                    $tuierArr = [$tuiidInfo['inituid']];
                    $task_nodeid = $tuiidInfo['nodeid'];
                    $task_name = $tuiidNode['name'];
                    $task_signtype = $tuiidNode['signtype'];
                    $task_plain = $tuiidNode['plain'];

                    FlowNodeModel::where(['id'=>$tuiidNode['id']])->update(['onshen'=>'']);
                }else{
                    if($param['tuiid'] > 0){
                        $tuiidInfo = FlowNodeModel::where(['id'=>$param['tuiid']])->find();
                        $tuitypeName = $tuiidInfo['name'];
                        $tuierArr = explode(',', $tuiidInfo['final']);
                        $task_plain = $tuiidInfo['plain'];
                        $task_signtype = $tuiidInfo['signtype'];
                        $task_nodeid = $tuiidInfo['id'];
                        $task_name = $tuiidInfo['name'];

                        FlowNodeModel::where(['id'=>$tuiidInfo['id']])->update(['onshen'=>'']);
                    }else{
                        FlowBillModel::where(['id'=>$bill['id']])->update(['recall'=>2]);
                        $tuierArr = [$bill['created_user']];
                        $task_name = '申请人重新提交';
                        $tuitypeName = '申请人发起申请';
                    }
                }

                //退回操作时， 其他执行钟的任务，全部暂停，并记录下来， 退回完成时（智能跳过时）才放开暂停的任务
                $ting = FlowTaskModel::where(['billid'=>$myTask['billid'],'nodeid'=>$myTask['nodeid'],'deleted_user'=>0,'state'=>1])->column('id');
                $tingids = implode(',', $ting);
                FlowTaskModel::where('id','in', $ting)->update(['state'=>0]);

                foreach ($tuierArr as $key=>$uid){
                    $state = 1;
                    if($task_plain > 0){
                        if($key > 0){
                            $state = 0;
                        }
                    }
                    FlowTaskModel::insert([
                        'comid' => $this->userinfo['comid'],
                        'billid' => $bill['id'],
                        'nodeid' => $task_nodeid,
                        'pid' => 0,
                        'name' => $task_name,
                        'signtype' => $task_signtype,
                        'plain' => $task_plain,
                        'uid' => $uid,
                        'isadd' => 1,
                        'opt' => 'tui',
                        'tuitype' => $param['tuitype'],
                        'tuiid' => $param['tuiid'],
                        'tuibeforeid' => $myTask['id'],
                        'tiaotype' => $param['tiaotype'],
                        'tingids' => $tingids,
                        'state' => $state,
                        'created_at' => date("Y-m-d H:i:s"),
                    ]);
                    if($state == 1){
                        (new WorkerService())->add_worker_bill($uid, 'tui', $bill);
                    }
                }

                (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'tui','退回('.$tuitypeName.')',1,$param['promer'],$myTask['created_at']);
                (new OptService())->add_flow_shenlog($myTask, '退回('.$tuitypeName.')',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
            }elseif($param['agree'] == 4){ //加签
                if(empty($param['adder'])){
                    throw new Exception('请选择加签人');
                }

                $existUname = '';
                $adderNmae = '';
                $onshenArr = explode(',', $node['onshen']);
                $adderArr = explode(',', $param['adder']);
                foreach ($adderArr as $addid){
                    $uname = UserModel::get_realname_by_pk($addid);
                    if(empty($adderNmae)){
                        $adderNmae .= $uname;
                    }else{
                        $adderNmae .= ','.$uname;
                    }
                    if(FlowTaskModel::where(['nodeid'=>$myTask['nodeid'],'uid'=>$addid,'deleted_user'=>0])->find() || in_array($addid, $onshenArr)){
                        if($existUname){
                            $existUname .= ','.$uname;
                        }else{
                            $existUname .= $uname;
                        }
                    }
                }
                if($existUname){
                    throw new Exception($existUname.'已在当前节点审核组,不能加签');
                }

                $signtype = 1;
                $plain = 0;
                $isadd = 1;

                if($param['addcate'] == 2){
                    $signtype = 2;
                    $isadd = 0;
                }elseif($param['addcate'] == 3){
                    $plain = 1;
                }

                foreach ($adderArr as $key=>$uid){
                    $state = 1;
                    if($plain == 1 && $key > 0){
                        $state = 0;
                    }
                    FlowTaskModel::insert([
                        'comid' => $this->userinfo['comid'],
                        'billid' => $bill['id'],
                        'nodeid' => $myTask['nodeid'],
                        'pid' => $myTask['id'],
                        'name' => $myTask['name'],
                        'signtype' => $signtype,
                        'plain' => $plain,
                        'uid' => $uid,
                        'isadd' => $isadd,
                        'opt' => 'add',
                        'addtype' => $param['addtype'],
                        'addcate' => $param['addcate'],
                        'state' => $state,
                        'created_at' => date("Y-m-d H:i:s"),
                    ]);
                    if($state == 1){
                        (new WorkerService())->add_worker_bill($uid, 'add', $bill);
                    }
                }


                if($param['addtype'] == 1){
                    FlowTaskModel::where(['id'=>$myTask['id']])->update([
                        'state'=>2,'updated_at'=>date('Y-m-d H:i:s'),'deleted_user'=>1
                    ]);
                    (new OptService())->add_flow_shenlog($myTask, '同意/加签('.$adderNmae.')',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
                }else{
                    FlowTaskModel::where(['id'=>$myTask['id']])->update(['state'=>0]);
                    (new OptService())->add_flow_shenlog($myTask, '加签('.$adderNmae.')',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
                }
                (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'add','加签('.$adderNmae.')',1,$param['promer'],$myTask['created_at']);
            }elseif($param['agree'] == 5){ //转签
                if(empty($param['zhuaner'])){
                    throw new Exception('请选择转签人');
                }

                $onshenArr = explode(',', $node['onshen']);
                $zhuanerName = UserModel::get_realname_by_pk($param['zhuaner']);
                if(FlowTaskModel::where(['nodeid'=>$myTask['nodeid'],'uid'=>$param['zhuaner'],'deleted_user'=>0])->find() || in_array($param['zhuaner'], $onshenArr)){
                    throw new Exception($zhuanerName.'已在当前节点审核组,不能转签');
                }

                FlowTaskModel::where(['id'=>$myTask['id']])->update(['uid'=>$param['zhuaner'],'zhuanuid'=>$myTask['uid']]);
                (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'zhuan','转签('.$zhuanerName.')',1,$param['promer'],$myTask['created_at']);
                (new WorkerService())->add_worker_bill($param['zhuaner'], 'zhuan', $bill);

                (new OptService())->add_flow_shenlog($myTask, '转签('.$zhuanerName.')',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files'], $qian_id, $qian);
            }elseif($param['agree'] == 6){ //退出审核
                if($myTask['opt'] != 'add'){
                    throw new Exception('不是加签人,无法退审');
                }

                $qiTask = FlowTaskModel::where(['billid'=>$myTask['billid'],'pid'=>$myTask['pid'],'deleted_user'=>0])->find();
                if($myTask['addcate'] == 2 && $qiTask){//被加签人或签
                    FlowTaskModel::where(['id'=>$myTask['id']])->update([
                        'state'=>2,'updated_at'=>date('Y-m-d H:i:s'),'deleted_user'=>1
                    ]);
                }else{
                    FlowTaskModel::where(['id'=>$myTask['id']])->update([
                        'state'=>2,'updated_at'=>date('Y-m-d H:i:s'),'deleted_user'=>1
                    ]);
                    (new FlowService())->flow_task_comple_linkage($myTask['id'], $minfo, $bill);

                    $existShen = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'deleted_user'=>0])
                        ->where('state','in',[0,1])->find();
                    if(!$existShen){
                        $nextNode = FlowNodeModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])
                            ->where('id','gt',$node['id'])->find();
                        if(!$nextNode){
                            FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>1]);
                            Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>1]);
                            (new FlowService())->flow_bill_succ($bill);
                        }else{
                            (new FlowService())->create_flow_node_task($nextNode, $minfo, $bill);
                        }
                    }
                }
                (new FlowService())->add_flow_task_shen($bill['id'],$node['id'],$myTask['id'],'out','退出审核',0,$param['promer'],$myTask['created_at']);
                (new OptService())->add_flow_shenlog($myTask, '退出审核',$this->userinfo['realname'], $param['explain'], $param['promer'], $param['files']);
            }

            $promerArr = explode(',', $param['promer']);
            foreach ($promerArr as $promerid){
                $mess = "抄送给我：[".$this->userinfo['realname']."]抄送的[".$bill['modename']."]，请查看！";
                (new WorkerService())->add_worker('bill', $promerid, '待办提醒', $mess, $bill['mid'], $bill['modenum']);
            }


            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function recall_bill(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['status'] != 0){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['recall'] < 1){
            return outputJson(4000, "流程已有审批记录，无法撤回");
        }

        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        Db::startTrans();
        try {
            FlowTaskModel::where(['billid'=>$bill['id']])->delete();
            FlowNodeModel::where(['billid'=>$bill['id']])->delete();
            FlowBillModel::where(['id'=>$bill['id']])->update([
                'isturn' => 0,
            ]);
            Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update([
                'isturn' => 0,
            ]);

            (new OptService())->add_flow_log('撤回', $bill['modenum'], $minfo['id']);
            (new OptService())->add_log_list('撤回', $bill['modenum'], $minfo['id'], $bill['modename']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function recall_shen(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['status'] != 0){
            return outputJson(4000,lang('code_4006'));
        }

        $taskShen = FlowTaskShenModel::where(['billid'=>$bill['id'],'uid'=>$this->userinfo['id'],'recall'=>1])
            ->where('opt','in',['add','zhuan','agree','tui', 'next'])->order('id DESC')->find();
        if(!$taskShen){
            return outputJson(4000, "流程已有审批记录，无法撤回");
        }

        $myTask = FlowTaskModel::where(['id'=>$taskShen['taskid']])->find();
        if(!$myTask){
            return outputJson(4000,lang('code_4006'));
        }

        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        Db::startTrans();
        try {

            $recallName = '撤回审核';
            if($taskShen['opt'] == 'add'){
                $recallName .= '(加签)';
                FlowTaskModel::where(['pid'=>$myTask['id']])->delete();
            }

            if($taskShen['opt'] == 'zhuan'){
                $recallName .= '(转签)';
                FlowTaskModel::where(['id'=>$myTask['id']])->update(['uid'=>$myTask['zhuanuid'],'zhuanuid'=>0]);
            }

            if($taskShen['opt'] == 'tui'){
                $recallName .= '(退回)';
                $tingids = FlowTaskModel::where(['billid'=>$bill['id'],'tuibeforeid'=>$myTask['id']])->value('tingids');
                FlowTaskModel::where('id','in', explode(',',$tingids))->update(['state'=>1]);
                FlowTaskModel::where(['billid'=>$bill['id'],'tuibeforeid'=>$myTask['id']])->delete();
            }

            if($taskShen['opt'] == 'agree'){
                $recallName .= '(同意)';
                $curTaskNodeid = FlowTaskModel::where(['billid'=>$bill['id'],'state'=>1,'deleted_user'=>0])->order('nodeid ASC')->value('nodeid');
                if($myTask['nodeid'] != $curTaskNodeid){
                    FlowTaskModel::where(['billid'=>$bill['id'],'nodeid'=>$curTaskNodeid])->delete();
                }
            }
            if($taskShen['opt'] == 'next'){
                $recallName .= '(同意)';
                FlowTaskModel::where(['pid'=>$myTask['id']])->delete();
            }


            //撤回审核节点记录的已审人信息（去掉当前用户）
            (new FlowService())->unset_flow_node_onshen($myTask['nodeid']);
            //当前任务撤回为进行中状态
            FlowTaskModel::where(['id'=>$myTask['id']])->update([
                'state'=>1,'updated_at'=>'','deleted_user'=>0
            ]);
            //删除任务审核记录
            FlowTaskShenModel::where(['id'=>$taskShen['id']])->delete();

            (new OptService())->add_flow_shenlog($myTask, $recallName,$this->userinfo['realname'], '','','');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function urge_bill(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['status'] != 0){
            return outputJson(4000,lang('code_4006'));
        }
        $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);
        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        $taskUid = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'state'=>1,'deleted_user'=>0])
            ->group('uid')->column('uid');


        Db::startTrans();
        try {
            foreach ($taskUid as $uid){
                (new WorkerService())->add_worker_bill($uid, 'urge', $bill);
            }
            (new OptService())->add_flow_log('催办', $bill['modenum'], $minfo['id']);
            (new OptService())->add_log_list('催办', $bill['modenum'], $minfo['id'], $bill['modename']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function share_bill(Request $request){
        $param = $request->post();

        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if(!in_array($bill['status'], [0,1,2])){
            return outputJson(4000,lang('code_4006'));
        }

        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        if(empty($param['domer'])){
            return outputJson(4000, "请选择分享给");
        }

        $param['comid'] = $this->userinfo['comid'];
        $param['billid'] = $bill['id'];
        $param['uid'] = $this->userinfo['id'];
        $param['created_user'] = $this->userinfo['id'];
        $param['created_at'] = date('Y-m-d H:i:s');
        unset($param['id']);
        unset($param['token']);

        Db::startTrans();
        try {
            $shareid = FlowShareModel::insertGetId($param);
            (new OptService())->add_flow_log('分享', $bill['modenum'], $minfo['id']);
            (new OptService())->add_log_list('分享', $bill['modenum'], $minfo['id'], $bill['modename']);

            $mess = "分享给我：[".$this->userinfo['realname']."]分享的[".$bill['modename']."]";
            foreach (explode(',', $param['domer']) as $uid){
                (new OptService())->add_todo($uid, $bill['modename'],$mess, $bill['mid'], $bill['modenum']);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function talk_bill(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if(!in_array($bill['status'], [0,1,2])){
                return outputJson(4000,lang('code_4006'));
            }
            $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);
            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }

            if(empty($param['domer'])){
                return outputJson(4000, "请选择评论给");
            }
            if(empty($param['explain'])){
                return outputJson(4000, "请输入评论内容");
            }

            $param['comid'] = $this->userinfo['comid'];
            $param['billid'] = $bill['id'];
            $param['uid'] = $this->userinfo['id'];
            $param['created_user'] = $this->userinfo['id'];
            $param['created_at'] = date('Y-m-d H:i:s');
            unset($param['id']);
            unset($param['token']);

            Db::startTrans();
            try {
                $talkid = FlowTalkModel::insertGetId($param);
                (new OptService())->add_flow_log('评论', $bill['modenum'], $minfo['id']);
                (new OptService())->add_log_list('评论', $bill['modenum'], $minfo['id'], $bill['modename']);

                $mess = "有新评论：[".$this->userinfo['realname']."]评论了[".$bill['created_user_name']."]发起的[".$bill['modename']."]";
                foreach (explode(',', $param['domer']) as $uid){
                    (new OptService())->add_todo($uid, $bill['modename'],$mess, $bill['mid'], $bill['modenum']);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->param('id',0,'int', 'int');
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$id])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if(!in_array($bill['status'], [0,1,2])){
                return outputJson(4000,lang('code_4006'));
            }

            $uidArr = FlowTaskModel::field('id,inituid')
                ->where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'pid'=>0,'state'=>2])
                ->order('created_at DESC')->group('uid')->column('uid');

            if(!in_array($bill['created_user'], $uidArr)){
                $uidArr[] = $bill['created_user'];
            }
            $data['domerArr'] = UserModel::field('*,id as value,realname as name')->where('id','in',$uidArr)->where(['deleted_user'=>0])->select()->toArray();
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function share_che(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $share = FlowShareModel::where(['id'=>$param['id'],'uid'=>$this->userinfo['id']])->find();
            if(!$share){
                return outputJson(4000,lang('code_4006'));
            }

            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$share['billid']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }

            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }


            Db::startTrans();
            try {
                FlowShareModel::where(['id'=>$share['id']])->delete();
                (new OptService())->add_flow_log('撤回分享', $bill['modenum'], $minfo['id']);
                (new OptService())->add_log_list('撤回分享', $bill['modenum'], $minfo['id'], $bill['modename']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4006'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(4000,lang('code_4006'));
    }

    public function promer_che(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $promer = FlowPromerModel::where(['id'=>$param['id'],'uid'=>$this->userinfo['id']])->find();
            if(!$promer){
                return outputJson(4000,lang('code_4006'));
            }

            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$promer['billid']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }

            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }


            Db::startTrans();
            try {
                FlowPromerModel::where(['id'=>$promer['id']])->delete();
                (new OptService())->add_flow_log('撤回抄送', $bill['modenum'], $minfo['id']);
                (new OptService())->add_log_list('撤回抄送', $bill['modenum'], $minfo['id'], $bill['modename']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,lang('code_4006'));
            }
            return outputJson(2000,lang('code_2000'));
        }
        return outputJson(4000,lang('code_4006'));
    }


    public function nullify_bill(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
        if(!in_array($bill['status'], [1,2])){
            return outputJson(4000,lang('code_4006'));
        }
        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>5]);
            Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>5]);
            (new FlowService())->add_flow_task_shen($bill['id'],0,0,'nullify','作废',0);
            $mess = "流程作废：您发起的[".$bill['summary']."]";
            (new OptService())->add_todo($bill['created_user'], $bill['modename'],$mess, $bill['mid'], $bill['modenum']);
            (new OptService())->add_flow_shenlog_direct($bill, '作废',$this->userinfo['realname']);
            (new OptService())->add_flow_log('作废', $bill['modenum'], $minfo['id']);
            (new OptService())->add_log_list('作废', $bill['modenum'], $minfo['id'], $bill['modename']);

            (new FlowService())->flow_bill_fail($bill);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function del_bill(Request $request){
        $param = $request->post();
        $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$bill){
            return outputJson(4000,lang('code_4006'));
        }
        if($bill['isturn'] != 1){
            return outputJson(4000,lang('code_4006'));
        }
//        if(!in_array($bill['status'], [3,5])){
//            return outputJson(4000,lang('code_4006'));
//        }
        $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
        if(!$minfo){
            return outputJson(4000,lang('code_4006'));
        }

        Db::startTrans();
        try {
            FlowBillModel::where(['id'=>$bill['id']])->update([
                'deleted_user'=>$this->userinfo['id'],
                'deleted_at'=>date("Y-m-d H:i:s")
            ]);
            Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update([
                'deleted_user'=>$this->userinfo['id'],
                'deleted_at'=>date("Y-m-d H:i:s")
            ]);
            (new OptService())->add_log_list(FlowLogModel::SET_DELETE, $bill['modenum'], $minfo['id'], $bill['modename']);

            (new FlowService())->flow_bill_fail($bill);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,$e->getMessage());
        }
        return outputJson(2000,lang('code_2000'));
    }

    public function transfer_bill(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }
            $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);
            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }

            if(empty($param['taskid'])){
                return outputJson(4000, "请选择原审核人");
            }
            if(empty($param['uid'])){
                return outputJson(4000, "请选择转签给");
            }


            $myTask = FlowTaskModel::where(['id'=>$param['taskid'],'state'=>1,'deleted_user'=>0])->find();
            if(!$myTask){
                return outputJson(4000,lang('code_4006'));
            }

            $node = FlowNodeModel::where(['id'=>$myTask['nodeid']])->find();
            if(!$node){
                return outputJson(4000,lang('code_4006'));
            }

            $onshenArr = explode(',', $node['onshen']);
            $zhuanerName = UserModel::get_realname_by_pk($param['uid']);
            if(FlowTaskModel::where(['nodeid'=>$myTask['nodeid'],'uid'=>$param['uid'],'deleted_user'=>0])->find() || in_array($param['uid'], $onshenArr)){
                return outputJson(4000, $zhuanerName.'已在当前节点审核组,不能转签');
            }

            $old_uid_name = UserModel::get_realname_by_pk($myTask['uid']);

            Db::startTrans();
            try {
                FlowTaskModel::where(['id'=>$myTask['id']])->update(['uid'=>$param['uid']]);
                FlowTaskShenModel::where(['billid'=>$myTask['billid']])->update(['recall'=>0]);
                (new FlowService())->add_flow_task_shen($bill['id'],$myTask['nodeid'],$myTask['id'],'zhuan_super','超管转签('.$old_uid_name.'-'.$zhuanerName.')',0);
                (new WorkerService())->add_worker_bill($param['uid'], 'zhuan', $bill);
                (new OptService())->add_flow_shenlog($myTask, '超管转签('.$old_uid_name.'-'.$zhuanerName.')',$this->userinfo['realname'], $param['explain']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->param('id',0,'int', 'int');
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$id])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }

            $taskidArr = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'state'=>1,'deleted_user'=>0])
                ->group('uid')->select()->toArray();
            foreach ($taskidArr as &$item){
                $item['uid_name'] = UserModel::get_realname_by_pk($item['uid']);
            }

            $data['taskidArr'] = $taskidArr;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function jumpshen_bill(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }
            $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);
            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }

            if(empty($param['taskid'])){
                return outputJson(4000, "请选择跳过审核人");
            }

            $myTask = FlowTaskModel::where(['id'=>$param['taskid'],'state'=>1,'deleted_user'=>0])->find();
            if(!$myTask){
                return outputJson(4000,lang('code_4006'));
            }

            $node = FlowNodeModel::where(['id'=>$myTask['nodeid']])->find();
            if(!$node){
                return outputJson(4000,lang('code_4006'));
            }

            $old_uid_name = UserModel::get_realname_by_pk($myTask['uid']);

            Db::startTrans();
            try {
                FlowTaskModel::where(['id'=>$myTask['id']])->update(['deleted_user'=>1]);
                (new FlowService())->flow_task_comple_linkage($myTask['id'], $minfo, $bill);

                $existShen = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'deleted_user'=>0])
                    ->where('state','in',[0,1])->find();
                if(!$existShen){
                    $nextNode = FlowNodeModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])
                        ->where('id','gt',$node['id'])->find();
                    if(!$nextNode){
                        FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>1]);
                        Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>1]);

                        (new FlowService())->flow_bill_succ($bill);
                    }else{
                        (new FlowService())->create_flow_node_task($nextNode, $minfo, $bill);
                    }
                }

                FlowTaskShenModel::where(['billid'=>$myTask['billid']])->update(['recall'=>0]);
                (new FlowService())->add_flow_task_shen($bill['id'],$myTask['nodeid'],$myTask['id'],'jumpshen','超管跳过审核人('.$old_uid_name.')',0);
                (new OptService())->add_flow_shenlog($myTask, '超管跳过审核人('.$old_uid_name.')',$this->userinfo['realname']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->param('id',0,'int', 'int');
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$id])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }

            $taskidArr = FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id'],'state'=>1,'deleted_user'=>0])
                ->group('uid')->select()->toArray();
            foreach ($taskidArr as &$item){
                $item['uid_name'] = UserModel::get_realname_by_pk($item['uid']);
            }

            $data['taskidArr'] = $taskidArr;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }

    public function jumpnode_bill(Request $request){
        if($request->isPost()){
            $param = $request->post();
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }
            $bill['created_user_name'] = UserModel::get_realname_by_pk($bill['created_user']);
            $minfo = Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->find();
            if(!$minfo){
                return outputJson(4000,lang('code_4006'));
            }

            if(empty($param['nodeid'])){
                return outputJson(4000, "请选择跳转到节点");
            }


            Db::startTrans();
            try {
                if($param['nodeid'] == -3){//结束-通过
                    FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>1]);
                    Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>1]);
                    (new FlowService())->flow_bill_succ($bill, $minfo);
                    $chuName = '超管(结束-通过)';
                }elseif($param['nodeid'] == -2){//结束-不通过
                    FlowBillModel::where(['id'=>$bill['id']])->update(['status'=>3]);
                    Db::name($bill['modenum'])->where(['id'=>$bill['mid']])->update(['status'=>3]);
                    $chuName = '超管(结束-不通过)';
                }elseif($param['nodeid'] == -1){//申请人重新提交
                    FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])->update(['deleted_user'=>1]);

                    FlowTaskModel::insert([
                        'comid' => $this->userinfo['comid'],
                        'billid' => $bill['id'],
                        'nodeid' => 0,
                        'pid' => 0,
                        'name' => '申请人重新提交',
                        'signtype' => 1,
                        'plain' => 0,
                        'uid' => $bill['created_user'],
                        'isadd' => 1,
                        'opt' => 'tui',
                        'tuitype' => 2,
                        'tuiid' => 0,
                        'tiaotype' => 1,
                        'tingids' => '',
                        'state' => 1,
                        'created_at' => date("Y-m-d H:i:s"),
                    ]);
                    $chuName = '超管跳转节点(申请人重新提交)';
                }else{ //跳转节点
                    FlowTaskModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])->update(['deleted_user'=>1]);
                    //生成审核任务
                    $tiaoNode = FlowNodeModel::where(['id'=>$param['nodeid']])->find();
                    (new FlowService())->create_flow_node_task($tiaoNode, $minfo, $bill);

                    $chuName = '超管跳转节点('.$tiaoNode['name'].')';
                }

                FlowTaskShenModel::where(['billid'=>$bill['id']])->update(['recall'=>0]);
                (new FlowService())->add_flow_task_shen($bill['id'],0,0,'jumpnode',$chuName,0);
                (new OptService())->add_flow_shenlog_direct($bill, $chuName, $this->userinfo['realname'], $param['explain']);

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return outputJson(4000,$e->getMessage());
            }
            return outputJson(2000,lang('code_2000'));
        }else{
            $id = $request->param('id',0,'int', 'int');
            $bill = FlowBillModel::where(['comid'=>$this->userinfo['comid'],'id'=>$id])->find();
            if(!$bill){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['isturn'] != 1){
                return outputJson(4000,lang('code_4006'));
            }
            if($bill['status'] != 0){
                return outputJson(4000,lang('code_4006'));
            }

            $nodeidArr = [];
            $nodeidArr[] = ['id'=>'-3','name'=>'结束(审核通过)'];
            $nodeidArr[] = ['id'=>'-2','name'=>'结束(审核不通过)'];

            $node = FlowNodeModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])->order('id DESC')->select()->toArray();
            foreach ($node as $v){
                $nodeidArr[] = ['id'=>$v['id'],'name'=>$v['name']];
            }

            $nodeidArr[] = ['id'=>'-1','name'=>'申请人重新提交'];

            $data['nodeidArr'] = $nodeidArr;
            return outputJson(2000,lang('code_2000'), $data);
        }
    }





    public function del_talk(Request $request){
        $param = $request->post();
        $talk = FlowTalkModel::where(['comid'=>$this->userinfo['comid'],'id'=>$param['id']])->find();
        if(!$talk){
            return outputJson(4000,lang('code_4006'));
        }
        if($talk['uid'] != $this->userinfo['comid']){
            return outputJson(4000,lang('code_4000'));
        }

        $bill = FlowBillModel::where(['id'=>$talk['billid']])->find();

        Db::startTrans();
        try {
            FlowTalkModel::where(['id'=>$talk['id']])->delete();
            (new OptService())->add_flow_log('删除评论', $bill['modenum'], $bill['mid']);
//            (new OptService())->add_log_list('删除评论', $bill['modenum'], $bill['mid'], $bill['modename']);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return outputJson(4000,lang('code_4000'));
        }

        $talk = FlowTalkModel::where(['comid'=>$this->userinfo['comid'],'billid'=>$bill['id']])->select()->toArray();
        foreach ($talk as &$item){
            $item['domer_name'] = UserModel::get_realname_by_ids($item['domer']);
            $item['uid_name'] = UserModel::get_realname_by_pk($item['uid']);
            $item['filesarr'] = FileModel::field('name,encpath,ext')->where('id','in',$item['files'])->select()->toArray();
            $item['isdel'] = $item['uid'] == $this->userinfo['id'] ? true : false;
        }
        $data['talk'] = $talk;

        return outputJson(2000,lang('code_2000'),$data);
    }
}
